<template>
	<div class="backg-box" style="background-color: rgba(149,144,150,0.3);">
		<!-- 主播顶端 -->
		<div class="top-box">
			<div class="header-box" >
				<image :src="image(infoList.liver_head)" mode="aspectFit" class="user"></image>
				<!-- <image src="../../../../static/12.gif" mode="aspectFit" class="user"></image> -->
				<!-- <image :src="$util.img(memberInfo.headimg) " mode="aspectFit" class="user"></image> -->
				<text class="title-size white-text" style="padding-left: 10rpx; padding-right: 20rpx;">{{infoList.liver_name}}</text>
			</div>
			<div style="position: fixed;
						top: 71rpx;
						right: 100rpx;
						height: 50rpx; 
						line-height: 50rpx;
						background-color: rgba(0,0,0,0.42);
						border-radius: 30rpx;
						padding-left: 30rpx;
						padding-right: 30rpx;
						padding-bottom: 10rpx;
			">
				<text style="color: #FFFFFF; font-size: 26rpx; line-height: 50rpx;"> {{people_number}} 人</text>
			</div>
			<div class="del" style=" width: 62rpx; height: 69rpx; position: fixed; right: 20rpx ; top: 60rpx;"  >
				<image src="../../../../static/del1.png" mode="aspectFit" style=" width: 62rpx; height: 69rpx;" @click="logoutLive()"></image>
			</div>
		</div>
		<image src="../../../../static/xj.png" mode="aspectFit" style=" width: 62rpx; height: 69rpx; position: fixed; right: 20rpx ; top: 260rpx;" @click="switchCamera()"></image>
		<tx_live_room ref="liveView" :style="`width: 100%;height: ${screenHeight}px;`">
		</tx_live_room>
		<tx_live_room ref="linkView" style=""></tx_live_room>
		<!-- 	<div  style="position: fixed;bottom: 20rpx;left:150rpx; width: 482rpx; height: 96rpx; border-radius: 50rpx; background-color: #F80926 ; justify-content: center; align-items: center;" @click="onClickLive()" v-if="startShow">
			<text style="color: #FFFFFF;">开始直播</text>
		</div> -->
		<!-- 	<button type="primary" style="position: fixed;bottom: 30px; right:10px"
		@click="onClickExit()">退出直播</button> -->
		<!-- 	<button type="primary" style="position: fixed;bottom:80px; right:10px"
			@click="onClickExitAnchor()">退出连麦</button> -->
		<!-- 	<button type="primary" style="position: fixed;bottom:130px; left:10px"
			@click="onClickGetAudienceList()">观众列表</button> -->
		<!-- <button type="primary" style="position: fixed;bottom:130px; right:10px" @click="onClickSendMsg()">发送消息</button> -->
		<!-- <div class=""> -->
		<list class="msg_box" :show-scrollbar="false" v-if="msgList.length > 0">
				<cell  v-for="(item,index) in msgList" :ref="`refMsg${index}`">
					<div class="cell-item">
						<image :src="image(item.userAvatar)" mode="aspectFit" class="user" style="margin-right: 14rpx;" v-if="item.userAvatar!= ''"></image>
						<image :src="defaultimg.default_headimg" mode="aspectFit" class="user" style="margin-right: 14rpx;" v-else></image>
						<text style="color: #FFD2C7; font-size: 28rpx;margin-top: 6px;">{{getName(item.userName, 5)}}:</text>
						<text class="fff-color">{{item.message}}</text> 
					</div>
					<div class="null" style="height: 20rpx;"></div>
				</cell>
		</list>
		<div style="position: fixed; left: 20rpx ; bottom: 24rpx;">
			<input type="text"  class="input-text"  style="" v-model="messages" placeholder="说点什么吧~"  placeholder-class="input-placeholder" maxlength="50" />
			<text style="position: fixed; left: 370rpx ;bottom: 24rpx; height: 72rpx; background-color: #FF4544; line-height:72rpx; color: #FFFFFF; border-radius: 40rpx; font-size: 26rpx; padding-left: 25rpx; padding-right: 25rpx; text-align: center;" @click="onClickSendMsg()">发送</text>
			 <image v-if="goodsList.length>0" src="../../../../static/img1.png" mode="aspectFit" style=" width: 62rpx; height: 69rpx; position: fixed; right: 30rpx ; bottom: 24rpx;" @click="open()"></image>
		</div>
		<uni-popup ref="storePopup" type="bottom">
			<view class="store-box" style="height:600rpx">
				<view class="" style="flex-direction: row;  align-items: stretch; padding: 10rpx; ">
					<view class="" style="width: 6rpx; height: 29rpx; line-height: 29rpx; background-color: red; margin-top: 5rpx;">	</view>
					<text style="margin-left: 13rpx; font-size: 32rpx;">直播商品</text>
					<image src="../../../../static/close.png" mode="aspectFit" style=" width: 62rpx; height: 69rpx; position: absolute; right: 30rpx ; top: 1rpx;" @click="close()"></image>
				</view>
				<list class="simple-douyin-list common-scroll mar-top-20" style="border-top-left-radius: 15px!important;">
					<cell class="shopping" v-for="(goodsitem,goodsindex) in goodsList" :key="goodsindex">
						<view class="store-list" style="">
							<image :src="goodsitem.sku_image" mode="aspectFill" class="store-list-iamge" style=""></image>
							<view class="" style="flex: 1; justify-content: space-between; height: 150rpx;">
								<text style="font-size: 28rpx;">{{goodsitem.sku_name}}</text>
								<view class="" style="flex-direction: row; justify-content: space-between; align-items: flex-end;">
									<view class="" style="flex-direction: row; ">
										<!-- <view class="" style=" height: 36rpx; margin-right: 10rpx; border-color: red;  ">
										</view> -->
										<!-- <text style="margin-left: 10rpx; margin-right: 10rpx; color: #FF4544!important; font-size: 32rpx; " >余额</text>
										<text style="font-size: 32rpx; color: #FF4544!important;">{{goodsitem.price}}</text> -->
										<text class="text-color-red" style="margin-left: 10rpx; margin-right: 10rpx; font-size: 32rpx; " >{{goodsitem.unit}}</text>
										<text class="text-color-red" style="font-size: 32rpx; ">{{goodsitem.price}}</text>
									</view>
									<view class="" style=" height: 50rpx; line-height: 50rpx; border-radius: 50rpx; margin-right: 20rpx;    background-color: #FF4544" @click="toShops(goodsitem.sku_id)">
										<text style="color: #FFFFFF; 
													font-size: 26rpx;
													margin-top: 10rpx;
													margin-bottom: 10rpx;
													margin-left: 30rpx;
													margin-right: 30rpx; 
										">去购买</text>
									</view>
								</view>
							</view>
						</view>
					</cell>
				</list>
			</view>
		</uni-popup>



	</div>
</template>

<script>
	 const dom = uni.requireNativePlugin('dom')
	import Util from '../../../../common/js/util.js'
	import Http from '../../../../common/js/http.js'
	import Config from '../../../../common/js/config.js'
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import permision from "@/js_sdk/wa-permission/permission.js";
	//LVB插件对象
	var sdkwx = uni.requireNativePlugin('TXMLVB-LiveRoom');
	export default {
		components: {
			uniPopup,
			Util
		},
		data() {
			return {
					msgList:[],//弹幕数组
					screenHeight: 0, //屏幕高度
					frontCamera: true, //默认摄像头
					startShow: true, //开始直播
					infoList:[],
					goodsList: [],
					Shows: false, //开播后
					info: [],
					btns: '',
					messageBtn:0,
					roomID:0,//房间号
					messages: '', //弹幕
					userInfo:[],
					defaultimg:[],
					people_number:0 //直播人数
			}
		},
	
		onLoad(option) {
			// 开启麦克风和摄像头
			// this.requestAndroidPermission('android.permission.CAMERA','android.permission.RECORD_AUDIO')
			this.screenHeight = wx.getSystemInfoSync().screenHeight;
			this.defaultimg = Util.getDefaultImage();
			//设置事件回调
			var that = this;
			sdkwx.setListener(function(res) {
				if (res.type == "onDebugLog") {
					return;
				}
				// console.log(res); //通过res.type == 'onXXX' 判断回调方法
				if (res.type == "onRequestJoinAnchor") { //处理连麦请求
					that.onRequestJoinAnchor(res.data);
				} else if (res.type == "onAnchorEnter") { //观众加入连麦
					that.onAnchorEnter(res.data);
				} else if (res.type == "onAnchorExit") { //连麦退出
					that.onAnchorExit(res.data);
				} else if (res.type == "onAudienceEnter") { //观众进入
					that.onAudienceEnter(res.data);
				} else if (res.type == "onAudienceExit") { //观众退出
					that.onAudienceExit(res.data);
				} else if (res.type == "onRecvRoomTextMsg") { //消息
					that.onRecvRoomTextMsg(res.data);
					// console.log("我收到消息了");
				} else if (res.type == "onRecvRoomCustomMsg") { //自定义消息
					var cmd = res.data.cmd;
					if (cmd == "onAudienceEnter") {
						// console.log(res.data.message);
						// that.Msg(res.data.message)
					} else if (cmd == "onAnchorExit") {
						// console.log(res.data.message);
					}
					that.onRecvRoomCustomMsg(res.data);
				}
			});
			// this.onClickLive()
			this.roomID =  option.roomID
			this.receiveMessage()
			this.init()
		},
		mounted() {},	
		onUnload() {
			let roomID = this.roomID
			this.onClickExit(roomID);
		 
			// this.logoutLive();
			// var liveView = this.$refs.liveView;
			// //停止本地视频预览
			// liveView.stopLocalPreview();
			// this.onClickLive()
			// setTimeout(() => {
			// 	this.btns = util.img('upload/uniapp/live/set_shops.png')
			// 	console.log(this.btns);
			// }, 300);
			

		},
		onShow() {
			setTimeout(() => {
				this.onClickLive()
				setInterval(()=>{
				    this.receiveMessage()
					this.getLivePelpleNumber();
					this.roomGoods();
				},5000)
			}, 300);
			
		},

		methods: {
			//切换摄像头
			switchCamera: function() {
				sdkwx.switchCamera({
					success: (a) => {
						console.log("livePusher.switchCamera:" + JSON.stringify(a));
					}
				});
			},
			getLivePelpleNumber(){
				Http.sendRequest({
					url: '/api/Memberliveplay/getLivePelpleNumber',
					data: {
						roomid: this.roomID
					},
					success: res => {
						this.people_number = res.data
						// console.log(res);
					}
				})
				
			},
			image(path){
				return Util.img(path);
			},
			// init
			init(){
				Http.sendRequest({
					url: '/api/Memberliveplay/roomInfoOpen',
					data: {
					},
					success: res => {
						this.userInfo = res
					}
				})
				
			},
			
			// 摄像头 麦克风
			async requestAndroidPermission(permisionID,permision_ID) {
				console.log('调用摄像头');
				var strStatus;
				permision.requestAndroidPermission(permisionID).then(res => {
					// if (result == 1) {
					// 	strStatus = "已获得授权"
					// } else if (result == 0) {
					// 	strStatus = "未获得授权"
					// } else {
					// 	strStatus = "被永久拒绝权限"
					// }
					// uni.showModal({
					// 	content: permisionID + strStatus,
					// 	showCancel: false
					// });
					permision.requestAndroidPermission(permision_ID)
				})
			},
			
			gotoAppPermissionSetting: function() {
				permision.gotoAppPermissionSetting()
			},
			open() {
				this.$refs.storePopup.open()
			},
			close(){
				this.$refs.storePopup.close()
			},
			roomGoods(){
				Http.sendRequest({
					url: '/api/Memberliveplay/roomInfo',
					data: {
						 roomid: this.roomID
					},
					success: res => {
						this.goodsList = res.goods_info
					}
				})
			},
			roomInfos() {
				Http.sendRequest({
					url: '/api/Memberliveplay/roomInfo',
					data: {
						 roomid: this.roomID
					},
					success: res => {
						console.log(res);
						this.infoList = res
						this.goodsList = res.goods_info
					}
				})
			},	
		
			// 购买商品
			toShops(sku_id) {
				uni.navigateTo({
					url: '/pages/goods/detail/detail?sku_id=' + sku_id
				});
			},
			
			onClickLive() {
				var liveView = this.$refs.liveView;

				//开始本地视频预览
				var frontCamera = true; //true:前置摄像头 false：后置摄像头
				liveView.startLocalPreview(frontCamera);

				//创建房间
				this.createRoom();
			},
			
			createRoom() {
				let that = this
				var roomId = that.roomID;//房间id
				var roomInfo = "";//房间信息
				console.log(that.roomID);
				// setTimeout(() => {
					sdkwx.createRoom(that.roomID, roomInfo, function(res){
						console.log(res);
						if(res.code >= 0){
							that.success()
						}else {
							uni.showModal({
								title: '提示',
								content: res.data,
								success: (res) => {
									uni.reLaunch({
										url: '/pages/member/index/index'
									});
								}
							});
						}
					});
				// }, 1000);
				
			},
			success() {
				let that = this;
				this.startShow = false
				this.Shows = true
				Http.sendRequest({
					url: '/api/Memberliveplay/startLive',
					data: {
						roomid: this.roomID,
					},
					success: res => {
						console.log(res);
						that.roomInfos()
					}
				})
			},
			// 退出直播
			logoutLive() {
				console.log('asd');
				let that = this;
				let roomID = this.roomID
				uni.showModal({
					title: '提示',
					content: '确定要退出直播吗',
					success: (res) => {
						if (res.confirm) {
							that.onClickExit(roomID)
						}
					}
				});
			},
			
			onClickExit(roomID) {
				let that = this;
				var liveView = this.$refs.liveView;
				
 
				liveView.stopLocalPreview();
				liveView.stopRemoteView();
					
					
				sdkwx.exitRoom(function(res) {
					console.log(res);
					sdkwx.logout();
	 			});
				
				Http.sendRequest({
					url: '/api/Memberliveplay/fellGroup',
					data: {roomid:roomID},
					success: res => {
						console.log(res);
						// 流量
						Http.sendRequest({
							url: '/api/Memberliveplay/exitLive',
							data: {
								 roomid: that.roomID
							},
							success: res => {
								console.log(res);
								that.people_number = res.people_number
								that.room_img = res.room_img
								uni.reLaunch({
									url: '/pages/member/index/index'
								});
							}
						})
					}
				})
				
			
				
			},
			/**
			 * 观众列表
			 */
			onClickGetAudienceList() {
				sdkwx.getAudienceList(this.roomID, function(res) {
					console.log(res);
				});
			},
			onRequestJoinAnchor(data) {
				var userID = data.anchorInfo.userID;
				var reason = data.reason;
				//主播同意连麦
				sdkwx.responseJoinAnchor(userID, true, reason, function(res) {
				})
			},
			onAnchorEnter(data) {
				var linkView = this.$refs.linkView;
				//开启远程连麦
				linkView.startRemoteView(data, function(res) {
				});                                                                                                            
			},
			onAnchorExit(data) {
				var linkView = this.$refs.linkView;
				//停止远程视频view
				linkView.stopRemoteView();
			},
			onAudienceEnter(data) {
			},
			onAudienceExit(data) {

			},
			
			
			onRecvRoomCustomMsg(data) {

			},
			onClickExitAnchor() {
				var linkView = this.$refs.linkView;
				//停止远程视频view
				linkView.stopRemoteView();

				//主播踢出连麦
				sdkwx.kickoutJoinAnchor("test11");
			},
			// 发送弹幕
			onClickSendMsg() {
				// 
				if (!this.messages.trim()) {
					uni.showToast({
						icon: 'none',
						title: '输入内容不为空'
					})
					return false;
				}
				
				let user = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo') : {'nickname':'用户','headimg': ''};
				const name  = user.nickname
				const headimg  = user.headimg
				let that = this
				let msg_data = {
					"message": this.messages,
					"userName": name,
					// "roomID": "71",
					"userID": uni.getStorageSync('live_uid'),
					"userAvatar": headimg
				};
				this.msgList.push(msg_data);
				if(this.msgList.length > 100) this.msgList.shift();
			
				
				//发送消息
				sdkwx.sendRoomTextMsg(this.messages, function(res) {
					that.messages = ''
				});
				
				this.messages = '';
				
				setTimeout(() => {
					this.$nextTick(()=>{  
						let index = this.msgList.length-1;
						let scrollToCell = this.$refs['refMsg'+index];
						if(scrollToCell){
							dom.scrollToElement(scrollToCell[0] , {});
						}
					})
				}, 200);
			 
				
			},
			// 接收弹幕
			onRecvRoomTextMsg(res){
				if(res){
					this.msgList.push(res);
					if(this.msgList.length > 100) this.msgList.shift();
					
					
					setTimeout(() => {
						this.$nextTick(()=>{  
							let index = this.msgList.length-1;
							let scrollToCell = this.$refs['refMsg'+index];
							if(scrollToCell){
								dom.scrollToElement(scrollToCell[0] , {});
							}
						})
					}, 200);
				}
			},
			Msg(message){
				
			},
			/**
			 * 购物车
			 */
			toCart() {
				uni.navigateTo({
					url: '/pages/goods/cart/cart'
				});
			},
			/**
			 * 直播间人数
			 */
			receiveMessage(){
				Http.sendRequest({
					url: '/api/Memberliveplay/receiveMessage',
					data: {
						roomid: this.roomID
					},
					success: res => {
						
					}
				})
			},
			getName(name, len){
				var disName =name;
				var shortName = disName.substring(0,len);
				if(name.length > 5){
				return shortName + '…';	
				}
				return shortName;
			},
		}
	}
</script>

<style>
	.input-placeholder{
		color: #FFFFFF;
		font-size: 14rpx;
		/* text-indent：10rpx; */
	}
	.text-color-red{
		color: #FF4544!important; 
	}
	.backg-box {
		background-color: rgba(149,144,150,0.3);
		/* background-color: #000000; */
		/* background: url(../../../../static/download/bgi.png); */
	}

	.store-list {
		flex-direction: row;
		align-items: center;
		margin: 10rpx 0;
	}

	.store-list-iamge {
		width: 170rpx;
		height: 150rpx;
		padding-left: 10rpx;
		padding-right: 20rpx;
	}

	.store-box {
		width: 750rpx;
		padding: 20rpx;
		background-color: #FFFFFF;
		position: fixed;
		bottom: 0px;
		left: 0px
	}
	
	/* header */

	.top-box {
		/* display: flex; */
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}
	
	.user {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
	}
	
	.title-size {
		font-size: 20rpx;
	}
	.white-text{
		font-size: 28rpx;
		color: #FFFFFF;
	}

	.exit-box {
		position: fixed;
		top: 60rpx;
		right: 10rpx;
		font-size: 40rpx;
		color: #FFFFFF;
		font-size: 24rpx!important;
	}

	.header-box {
		position: fixed;
		top: 60rpx;
		left: 30rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		/* background-color: #9A9B9E; */
		background-color: rgba(0,0,0,0.5);
		/* background-color: rgba(0,0,0,0.6); */
		/* background-color: #07C160; */
		border-radius: 40rpx;
		padding: 5rpx 10rpx;
	}

	.box-sizing {
		box-sizing: border-box;
	}

	.footer_box {
		/* position: fixed;
		bottom: 20rpx;
		margin: 0 20rpx;
		background-color: red; */
	}

	.footer_img {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
	}
	
	/* 弹幕 */
	.input-text{
		width: 332rpx;
		height: 72rpx; 
		background-color: rgba(149,144,150,0.3);
		border-radius: 50rpx;
		padding-left: 25rpx; 
		padding-right: 25rpx;
		color: #FFFFFF;
	}
	
	.msg_box{
		display: flex;
		flex-direction: column;
		position: fixed;
		bottom: 120rpx;
		max-height:600rpx;
		overflow-y:auto;
		left: 40rpx;
		background-color: rgba(0,0,0,0.1);
		padding: 20rpx 20rpx 3rpx 20rpx;
		border-radius: 10px;
	}
	
	.cell-item{
		max-width:492rpx;
		
		padding: 3rpx 20rpx 3rpx 3rpx;
		
		white-space:normal;
		display: flex;
		flex-direction: row;
		align-items: center;
		width: fit-content;
		align-items: flex-start;
	}
	.fff-color{
		color: #fff;
		font-size: 27rpx;
		line-height: 27rpx;
		margin-left: 19rpx;
		flex: 1;
		word-break: break-all;
		    margin-top: 9px;
	}
	
	.msg_box::-webkit-scrollbar{display: none;}
	
</style>
